package com.cn.medicalcare.service.serviceimpl;

import com.cn.medicalcare.customtool.JedisUtil;
import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.AllPage;
import com.cn.medicalcare.pojo.Message;
import com.cn.medicalcare.pojo.Page;
import com.cn.medicalcare.service.MessageService;

import java.util.*;

public class MessageServiceImpl implements MessageService {

    private static final long SYSTEM_TIME = 1592278506978L;

    private static final String MESSAGES_NAME = "MESSAGES_SortedSet";

    //静态内部类单例模式
    private static class SingletonClassInstance {
        private static final MessageServiceImpl instance = new MessageServiceImpl();
    }

    private MessageServiceImpl() {
    }

    public static MessageServiceImpl getInstance() {
        return MessageServiceImpl.SingletonClassInstance.instance;
    }


    @Override
    public boolean insertMessage(Message message) {
        Double messageID = (new Date().getTime() - SYSTEM_TIME) / 10000.0;
        message.setId(messageID);
        String messageJson = JsonTool.toJson(message);
        long result = JedisUtil.jedisDo(j -> {
            j.select(14);
            return j.zadd(MESSAGES_NAME, messageID, messageJson);
        });
        return result > 0;
    }

    @Override
    public int selectMessageCount() {
        long count = JedisUtil.jedisDo(j -> {
            j.select(14);
            return j.zcard(MESSAGES_NAME);
        });
        return (int) count;
    }

    @Override
    public List<Message> selectMessageInPage(Page page) {
        Set<String> messagestrs = JedisUtil.jedisDo(j -> {
            j.select(14);
            return j.zrevrange(MESSAGES_NAME, page.getSkip(), page.getLimit());
        });
        List<Message> list = new LinkedList<>();
        if (messagestrs != null && !messagestrs.isEmpty())
            for (String meg : messagestrs) {
                list.add(JsonTool.toObject(meg, Message.class));
            }
        return list;
    }
}
